package com.gengine.ui.timer
{
	import com.gengine.core.frame.*;
	
	import flash.display.*;
	import flash.text.*;
	
	public class GameClock extends Sprite
	{
		private var _year:int;
		private var _month:int;
		private var _date:int;
		private var _hours:int;
		private var _minutes:int;
		private var _seconds:int;
		private var _time:Number;
		private var _nowDate:Date;
		private var _secTimer:SecTimer;
		private var _label:TextField;
		public var enterFrameHandler:Function;
		
		public function GameClock()
		{
			this.mouseChildren = false;
			this.mouseEnabled = false;
			this._label = new TextField();
			this._label.mouseEnabled = false;
			this._label.autoSize = TextFieldAutoSize.CENTER;
			this._label.defaultTextFormat = new TextFormat(null, 12);
			this.addChild(this._label);
			this._secTimer = new SecTimer();
			this._secTimer.addListener(TimerType.ENTERFRAME, this.onEnterFrameHandler);
		}
		
		private function onEnterFrameHandler(event:SecTimer) : void
		{
			this._nowDate.seconds = this._nowDate.seconds + 1;
			
			if (this.parent)
			{
				this._label.text = getDateStr();
			}
			
			if (this.enterFrameHandler is Function)
			{
				this.enterFrameHandler(this._nowDate);
			}
		}
		
		private function getDateStr() : String
		{
			var dateStr:String = "";
			dateStr = dateStr + (this._nowDate.fullYear + "-");
			if (this._nowDate.month < 10)
			{
				dateStr = dateStr + "0";
			}
			dateStr = dateStr + ((this._nowDate.month + 1) + "-");
			if (this._nowDate.date < 10)
			{
				dateStr = dateStr + "0";
			}
			dateStr = dateStr + (this._nowDate.date + "  ");
			if (this._nowDate.hours < 10)
			{
				dateStr = dateStr + "0";
			}
			dateStr = dateStr + (this._nowDate.hours + ":");
			if (this._nowDate.minutes < 10)
			{
				dateStr = dateStr + "0";
			}
			dateStr = dateStr + (this._nowDate.minutes + ":");
			if (this._nowDate.seconds < 10)
			{
				dateStr = dateStr + "0";
			}
			dateStr = dateStr + this._nowDate.seconds;
			
			return dateStr;
		}
		
		public function set time (data:Object) : void
		{
			if (data is Date)
			{
				this._nowDate = data as Date;
			}
			else
			{
				if (data is Number)
				{
					this._time = data as Number;
				}
				this._nowDate = new Date(_time);
			}
			
			if (_secTimer.running == false)
			{
				_secTimer.start();
			}		
		}
		
		public function get nowDate() : Date
		{
			return this._nowDate;
		}
	}
}